package com.example.bbbb.beanlifecycle;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-02-01
 * Time: 19:58
 */

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {


    // 4. BeanPostProcessor 的 before
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("user")) {
            System.out.println("4. BeanPostProcessor 的 postProcessBeforeInitialization 执行了 -> " +
                    "user 对象初始化方法前开始增强");
        }
        return bean;
    }

    // 6. BeanPostProcessor 的 after
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        if (beanName.equals("user")) {
            System.out.println("6. BeanPostProcessor 的 postProcessAfterInitialization 执行了 -> " +
                    "user 对象初始化方法后开始增强，即代理");
            // 6.1
            // cglib 代理对象
            Enhancer enhancer = new Enhancer();
            // 设置需要增强的类
            enhancer.setSuperclass(bean.getClass());
            // 执行回调方法，增强方法
            enhancer.setCallback(new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    // 执行目标方法
                    // 一系列增强逻辑......
                    System.out.println("6.1 代理对象执行了增强的方法 ");
                    return method.invoke(method, args);
                }
            });
            // 返回代理对象
            return enhancer.create();
        }

        return bean;
    }


}
